<?php

namespace App\Http\Controllers\Admin;

use App\Models\BookHomePurchaseSet;
use App\Models\OweOrder;
use App\Models\UserInfo;

/**
 * 欠费模块
 * Class PayInfo
 * @package app\port\controlle
 */
class OweProcessController extends CommonController
{

    public function __construct()
    {
        parent::__construct();
    }

    /**
     * 缴纳的欠费列表
     * @param $authorrization ：用户 token  可选
     * @param page 页数 默认为1
     * @param limit 限制条数 默认 10
     * @param keywords 检索条件
     * @param payment 支付方式  1 微信支付   2 积分抵扣  3其他
     */
    public function lists()
    {
        $page = request()->input('page', 1);
        $limit = request()->input('limit', 10);
        $start_time = request()->input('start_time');
        $end_time = request()->input('end_time');
        $keywords = request()->input('keywords');
        $payment = request()->input('payment');
        $is_pay = 2; //需要已支付的

        $oweOrderModelObj = new OweOrder();
        $res =  $oweOrderModelObj->lists($keywords, $payment, $is_pay, $start_time, $end_time, $limit);
        if ($res['data']) {
            $score = 0;
            $price = 0;
            $deduction_price = 0;
            foreach ($res['data'] as $key => $val) {
                if ($val['payment'] == 1) {
                    $price +=  $val['price'];
                } else {
                    $deduction_price +=  $val['price'];
                    $score +=  $val['score'];
                }
                $res['data'][$key]['nickname'] = UserInfo::getWechatField($val['user_id'], 'nickname');
            }

            $res = $this->disPageData($res);
            $res['data'] = $this->addSerialNumber($res['data'], $page, $limit);


            $res['score'] = $score;
            $res['price'] = sprintf("%.2f", $price);
            $res['deduction_price'] = sprintf("%.2f", $deduction_price);
            //获取积分抵扣数据
            $res['subscription_ratio'] = BookHomePurchaseSet::where('type', 15)->value('number');

            return $this->returnApi(200, '获取成功', true, $res);
        }
        return $this->returnApi(203, '暂无数据');
    }


    /**
     * 欠费缴纳积分抵扣设置
     * @param number  数量 设置0或空，表示关闭此功能
     */
    public function subscriptionRatioSet()
    {
        $number = $this->request->number;
        if (empty(trim($number)) || !is_numeric($number)) {
            $number = 0; //0表示关闭
        }
        $bookHomePurchaseSetModel = new BookHomePurchaseSet();
        $res = $bookHomePurchaseSetModel->where('type', 15)->first();
        if ($res) {
            $res->number = $number; //内容存放在number
            $result = $res->save();
        } else {
            $bookHomePurchaseSetModel->type = 15;
            $bookHomePurchaseSetModel->number = $number; //内容存放在number
            $result = $bookHomePurchaseSetModel->save();
        }

        if ($result) {
            return $this->returnApi(200, '设置成功', true);
        } else {
            return $this->returnApi(202, '设置失败');
        }
    }
}
